package com.hbnu.jdbc;

import java.sql.*;

/**
 * @author kittychen
 * @since 2025-10-24 9:11
 */
public class JdbcDemo06 {

    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        String url = "jdbc:mysql://127.0.0.1:3306/class2311?serverTimezone=GMT&useSSL=false&characterEncoding=utf8";
        String name = "root";
        String pwd = "123456";

        try {
            connection = DriverManager.getConnection(url, name, pwd);

            // 开启事务
            connection.setAutoCommit(false);

            String sql1 = "update tb_user set salary = salary - ? where username = ?";
            String sql2 = "update tb_user set salary = salary + ? where username = ?";

            // 转账
            preparedStatement = connection.prepareStatement(sql1);
            preparedStatement.setDouble(1, 1000);
            preparedStatement.setString(2, "张三");
            int count = preparedStatement.executeUpdate();

            int i = 1 / 0;

            // 收款
            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.setDouble(1, 1000);
            preparedStatement.setString(2, "王五");
            count += preparedStatement.executeUpdate();

            // 提交事务
            connection.commit();

            System.out.println(count == 2 ? "转账成功" : "转账失败");
        } catch (Exception e) {
            try {
                // 回滚事务
                if (connection != null) {
                    connection.rollback();
                    System.out.println("转账失败");
                }
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
        } finally {
            try {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }

            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
